// pages/merchant/user-management/index.js
const apiService = require('../../../utils/api.js');
const amount = require('../../../utils/amount.js');

// 高余额筛选阈值（单位：分），默认500元
const HIGH_BALANCE_THRESHOLD_CENTS = 50000;

Page({
  data: {
    // 用户统计（单位：分）
    userStats: {
      total: 0,
      active: 0,
      newToday: 0,
      totalBalance: 0,
      totalBalanceDisplay: '0.00'
    },
    
    // 用户列表
    userList: [],
    filteredUsers: [],
    
    // 筛选条件
    currentFilter: 'all',
    searchKeyword: '',
    
    // 加载状态
    isLoading: false,
    
    // 弹窗状态
    showRechargeModal: false,
    showDeductModal: false,
    showUserDetailModal: false,
    
    // 选中的用户
    selectedUser: {},
    
    // 充值相关
    rechargeAmount: '',
    rechargeNote: '',
    
    // 扣费相关
    deductAmount: '',
    deductNote: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('用户管理页面加载', options);
    this.loadUserList();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.loadUserList();
  },

  /**
   * 加载用户列表
   */
  async loadUserList() {
    this.setData({ isLoading: true });
    try {
      // 模拟用户数据（单位：分），实际项目中应该调用API
      const mockUsers = [
        {
          userId: 'user_001',
          nickName: '张小明',
          phone: '138****1234',
          avatarUrl: '/images/default_avatar.png',
          balance: 35000,
          isVip: true,
          registerTime: '2024-01-15',
          totalOrders: 25,
          totalSpent: 120000,
          totalRecharge: 150000,
          lastOrderTime: '2024-01-24 16:30'
        },
        {
          userId: 'user_002',
          nickName: '李小红',
          phone: '139****5678',
          avatarUrl: '/images/default_avatar.png',
          balance: 8800,
          isVip: false,
          registerTime: '2024-01-20',
          totalOrders: 8,
          totalSpent: 40000,
          totalRecharge: 50000,
          lastOrderTime: '2024-01-23 14:20'
        },
        {
          userId: 'user_003',
          nickName: '王小强',
          phone: '137****9012',
          avatarUrl: '/images/default_avatar.png',
          balance: 120000,
          isVip: true,
          registerTime: '2024-01-10',
          totalOrders: 45,
          totalSpent: 280000,
          totalRecharge: 300000,
          lastOrderTime: '2024-01-25 10:15'
        },
        {
          userId: 'user_004',
          nickName: '赵小美',
          phone: '136****3456',
          avatarUrl: '/images/default_avatar.png',
          balance: 2500,
          isVip: false,
          registerTime: '2024-01-22',
          totalOrders: 3,
          totalSpent: 15000,
          totalRecharge: 20000,
          lastOrderTime: '2024-01-24 09:45'
        },
        {
          userId: 'user_005',
          nickName: '陈小华',
          phone: '135****7890',
          avatarUrl: '/images/default_avatar.png',
          balance: 68000,
          isVip: false,
          registerTime: '2024-01-18',
          totalOrders: 15,
          totalSpent: 80000,
          totalRecharge: 100000,
          lastOrderTime: '2024-01-25 15:30'
        }
      ];

      // 计算统计数据（分）
      const stats = {
        total: mockUsers.length,
        active: mockUsers.filter(u => u.totalOrders > 0).length,
        newToday: mockUsers.filter(u => u.registerTime === '2024-01-25').length,
        totalBalance: mockUsers.reduce((sum, u) => sum + (u.balance || 0), 0)
      };

      // 格式化用户数据，添加显示字段
      const formattedUsers = mockUsers.map(user => ({
        ...user,
        balanceDisplay: (user.balance / 100).toFixed(2)
      }));

      this.setData({
        userList: formattedUsers,
        filteredUsers: formattedUsers,
        userStats: {
          ...stats,
          totalBalanceDisplay: (stats.totalBalance / 100).toFixed(2)
        }
      });

    } catch (error) {
      console.error('加载用户列表失败:', error);
      wx.showToast({ title: '加载失败', icon: 'none' });
    } finally {
      this.setData({ isLoading: false });
    }
  },

  /**
   * 搜索输入
   */
  onSearchInput(e) {
    this.setData({ searchKeyword: e.detail.value });
  },

  /**
   * 搜索
   */
  onSearch() {
    this.filterUsers();
  },

  /**
   * 筛选条件改变
   */
  onFilterChange(e) {
    const filter = e.currentTarget.dataset.filter;
    this.setData({ currentFilter: filter });
    this.filterUsers();
  },

  /**
   * 筛选用户
   */
  filterUsers() {
    const { userList, currentFilter, searchKeyword } = this.data;
    let filtered = [...userList];

    // 按类型筛选
    if (currentFilter === 'vip') {
      filtered = filtered.filter(user => user.isVip);
    } else if (currentFilter === 'high_balance') {
      // 以分为单位的高余额筛选
      filtered = filtered.filter(user => (user.balance || 0) >= HIGH_BALANCE_THRESHOLD_CENTS);
    }

    // 按关键词搜索
    if (searchKeyword.trim()) {
      const keyword = searchKeyword.trim().toLowerCase();
      filtered = filtered.filter(user => 
        (user.nickName || '').toLowerCase().includes(keyword) ||
        (user.phone || '').includes(keyword) ||
        (user.userId || '').toLowerCase().includes(keyword)
      );
    }

    this.setData({ filteredUsers: filtered });
  },

  /**
   * 用户点击
   */
  onUserTap(e) {
    const user = e.currentTarget.dataset.user;
    console.log('点击用户:', user);
  },

  /**
   * 充值用户
   */
  onRechargeUser(e) {
    const user = e.currentTarget.dataset.user;
    // 为选中的用户添加显示字段
    const formattedUser = {
      ...user,
      balanceDisplay: (user.balance / 100).toFixed(2)
    };
    this.setData({
      selectedUser: formattedUser,
      rechargeAmount: '',
      rechargeNote: '',
      showRechargeModal: true
    });
  },

  /**
   * 扣费用户
   */
  onDeductUser(e) {
    const user = e.currentTarget.dataset.user;
    // 为选中的用户添加显示字段
    const formattedUser = {
      ...user,
      balanceDisplay: (user.balance / 100).toFixed(2)
    };
    this.setData({
      selectedUser: formattedUser,
      deductAmount: '',
      deductNote: '',
      showDeductModal: true
    });
  },

  /**
   * 关闭扣费弹窗
   */
  onCloseDeductModal() {
    this.setData({ showDeductModal: false });
  },

  /**
   * 扣费说明输入
   */
  onDeductNoteInput(e) {
    this.setData({ deductNote: e.detail.value });
  },

  /**
   * 关闭充值弹窗
   */
  onCloseRechargeModal() {
    this.setData({ showRechargeModal: false });
  },

  /**
   * 充值金额输入（单位：元，输入框为元） */
  onRechargeAmountInput(e) {
    this.setData({ rechargeAmount: e.detail.value });
  },

  /** 快速选择金额（元） */
  onSelectAmount(e) {
    const amountYuan = e.currentTarget.dataset.amount;
    this.setData({ rechargeAmount: amountYuan });
  },

  /** 确认充值：将元转换为分进行计算与存储 */
  async onConfirmRecharge() {
    const { selectedUser, rechargeAmount, rechargeNote } = this.data;
    const cents = amount.yuanToCent(rechargeAmount);
    if (!cents || cents <= 0) {
      wx.showToast({ title: '请输入有效金额', icon: 'none' });
      return;
    }
    wx.showLoading({ title: '处理中...' });
    try {
      const userList = this.data.userList.map(user => {
        if (user.userId === selectedUser.userId) {
          const newBalance = (user.balance || 0) + cents;
          return {
            ...user,
            balance: newBalance,
            balanceDisplay: (newBalance / 100).toFixed(2),
            totalRecharge: (user.totalRecharge || 0) + cents
          };
        }
        return user;
      });
      const stats = {
        total: userList.length,
        active: userList.filter(u => u.totalOrders > 0).length,
        newToday: userList.filter(u => u.registerTime === '2024-01-25').length,
        totalBalance: userList.reduce((sum, u) => sum + (u.balance || 0), 0)
      };
      this.setData({ 
        userList, 
        userStats: {
          ...stats,
          totalBalanceDisplay: (stats.totalBalance / 100).toFixed(2)
        }, 
        showRechargeModal: false 
      });
      this.filterUsers();
      wx.showToast({ title: '充值成功', icon: 'success' });
    } catch (error) {
      console.error('充值失败:', error);
      wx.showToast({ title: '充值失败', icon: 'none' });
    } finally {
      wx.hideLoading();
    }
  },

  /** 扣费金额输入（单位：元，输入框为元） */
  onDeductAmountInput(e) {
    this.setData({ deductAmount: e.detail.value });
  },

  /** 确认扣费：校验与提示仍按元显示，但计算按分执行 */
  async onConfirmDeduct() {
    const { selectedUser, deductAmount, deductNote } = this.data;
    const cents = amount.yuanToCent(deductAmount);
    if (!cents || cents <= 0) {
      wx.showToast({ title: '请输入有效金额', icon: 'none' });
      return;
    }
    if (!deductNote || !deductNote.trim()) {
      wx.showToast({ title: '请输入扣费原因', icon: 'none' });
      return;
    }
    if (cents > (selectedUser.balance || 0)) {
      wx.showToast({ title: '扣费金额不能超过余额', icon: 'none' });
      return;
    }
    wx.showModal({
      title: '确认扣费',
      content: `确定要从用户"${selectedUser.nickName}"账户扣费¥${amount.formatYuan(deductAmount)}吗？`,
      success: async (res) => { if (res.confirm) { await this.executeDeduct(); } }
    });
  },

  /** 执行扣费：内部统一用分 */
  async executeDeduct() {
    const { selectedUser, deductAmount, deductNote } = this.data;
    const cents = amount.yuanToCent(deductAmount);
    wx.showLoading({ title: '处理中...' });
    try {
      const userList = this.data.userList.map(user => {
        if (user.userId === selectedUser.userId) {
          const newBalance = (user.balance || 0) - cents;
          return {
            ...user,
            balance: newBalance,
            balanceDisplay: (newBalance / 100).toFixed(2),
            totalSpent: (user.totalSpent || 0) + cents
          };
        }
        return user;
      });
      const stats = {
        total: userList.length,
        active: userList.filter(u => u.totalOrders > 0).length,
        newToday: userList.filter(u => u.registerTime === '2024-01-25').length,
        totalBalance: userList.reduce((sum, u) => sum + (u.balance || 0), 0)
      };
      this.setData({ 
        userList, 
        userStats: {
          ...stats,
          totalBalanceDisplay: (stats.totalBalance / 100).toFixed(2)
        }, 
        showDeductModal: false 
      });
      this.filterUsers();
      wx.showToast({ title: '扣费成功', icon: 'success' });
    } catch (error) {
      console.error('扣费失败:', error);
      wx.showToast({ title: '扣费失败', icon: 'none' });
    } finally { wx.hideLoading(); }
  },

  /**
   * 查看用户详情
   */
  onViewUserDetail(e) {
    const user = e.currentTarget.dataset.user;
    // 为选中的用户添加显示字段
    const formattedUser = {
      ...user,
      balanceDisplay: (user.balance / 100).toFixed(2),
      totalSpentDisplay: ((user.totalSpent || 0) / 100).toFixed(2),
      totalRechargeDisplay: ((user.totalRecharge || 0) / 100).toFixed(2)
    };
    this.setData({
      selectedUser: formattedUser,
      showUserDetailModal: true
    });
  },

  /**
   * 关闭用户详情弹窗
   */
  onCloseUserDetailModal() {
    this.setData({ showUserDetailModal: false });
  },

  /**
   * 防止弹窗滚动穿透
   */
  preventTouchMove() {
    return false;
  }
});